package com.hhit.zhgd.task

import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.hhit.zhgd.component.WeatherApiProperties
import com.hhit.zhgd.dao.ZhgdWeatherMapper
import com.hhit.zhgd.domain.entity.ZhgdWeather
import com.hhit.zhgd.utils.formatString
import jakarta.annotation.Resource
import org.quartz.JobExecutionContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.quartz.QuartzJobBean
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.util.*
import java.util.function.Consumer


class WeatherTask : QuartzJobBean() {

    @Resource
    private var weatherApiProperties: WeatherApiProperties? = null

    @Autowired
    private var zhgdWeatherMapper: ZhgdWeatherMapper? = null
    override fun executeInternal(context: JobExecutionContext) {
        val request = HttpRequest.newBuilder()
            .uri(
                URI.create(
                    weatherApiProperties?.requrl
                        ?: "" + "?city=" + weatherApiProperties?.cityName + "&key=" + weatherApiProperties?.appkey
                )
            )
            .GET()
            .build()
        val response: HttpResponse<String> = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString())

        //val response: String = HttpUtil.get(weatherApiProperties.getRequrl(), params)
        try {
            val jsonObject = JSONObject.parseObject(response.body())
            val errorCode = jsonObject.getIntValue("error_code")
            if (errorCode == 0) {
                println("调用接口成功")
                val result = jsonObject.getJSONObject("result")
                val realtime = result.getJSONObject("realtime")
                val city = result.getString("city")
                val info = realtime.getString("info")
                val temperature1 = realtime.getString("temperature")
                val humidity = realtime.getString("humidity")
                val direct1 = realtime.getString("direct")
                val power = realtime.getString("power")
                val aqi = realtime.getString("aqi")
                val time: String = Date().formatString("yyyy-MM-dd")
                var zhgdWeather = zhgdWeatherMapper!!.selectOne(
                    LambdaQueryWrapper<ZhgdWeather>()
                        .eq(ZhgdWeather::cityName, city).eq(ZhgdWeather::createTime, time)
                )
                if (zhgdWeather == null) {
                    zhgdWeather = ZhgdWeather(
                        source = 2,
                        cityName = city,
                        wea = info,
                        temperature = temperature1,
                        win = direct1,
                        windspeed = power,
                        pm25 = aqi,
                        humidity = humidity,
                        createTime = time
                    )
                    zhgdWeatherMapper!!.insert(zhgdWeather)
                } else {
                    zhgdWeather.source = 2
                    zhgdWeather.cityName = city
                    zhgdWeather.wea = info
                    zhgdWeather.temperature = temperature1
                    zhgdWeather.win = direct1
                    zhgdWeather.windspeed = power
                    zhgdWeather.pm25 = aqi
                    zhgdWeather.humidity = humidity
                    zhgdWeather.createTime = time
                    zhgdWeatherMapper!!.updateById(zhgdWeather)
                }
                val futures = result.getJSONArray("future")
                futures.forEach(Consumer<Any> { item: Any? ->
                    val future =
                        JSONObject.parseObject(JSONObject.toJSONString(item))
                    val date = future.getString("date")
                    val temperature = future.getString("temperature")
                    val weather = future.getString("weather")
                    val direct = future.getString("direct")
                    // 移除温度单位 "℃"
                    val tempRangeWithoutUnit = temperature.substring(0, temperature.length - 1)
                    // 使用斜杠("/")分割字符串
                    val temperatures =
                        tempRangeWithoutUnit.split("/".toRegex()).dropLastWhile { it.isEmpty() }
                            .toTypedArray()
                    var zhgdWeather1 =
                        zhgdWeatherMapper!!.selectOne(
                            LambdaQueryWrapper<ZhgdWeather>().eq(
                                ZhgdWeather::createTime,
                                date
                            )
                        )
                    if (zhgdWeather1 == null) {
                        zhgdWeather1 = ZhgdWeather(
                            source = 2,
                            cityName = city,
                            wea = weather,
                            temDay = temperatures[1],
                            temNight = temperatures[0],
                            win = direct,
                            createTime = date
                        )
                        zhgdWeatherMapper!!.insert(zhgdWeather1)
                    } else {
                        zhgdWeather1.source = 2
                        zhgdWeather1.cityName = city
                        zhgdWeather1.wea = weather
                        zhgdWeather1.temDay = temperatures[1]
                        zhgdWeather1.temNight = temperatures[0]
                        zhgdWeather1.win = direct
                        zhgdWeather1.createTime = date
                        zhgdWeatherMapper!!.updateById(zhgdWeather1)
                    }
                })
            } else {
                println("调用接口失败：" + jsonObject.getString("reason"))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

fun main(args: Array<String>) {
//    val params: MutableMap<String, Any> = HashMap() //组合参数
//    params["city"] = "南通"
//    params["key"] = "e4ea00ef9fe29f87ae151faeaced840f"
//    val response: String = HttpUtil.get("http://apis.juhe.cn/simpleWeather/query", params)
    val request = HttpRequest.newBuilder()
        .uri(
            URI.create(
                "http://apis.juhe.cn/simpleWeather/query?city=南通&key=e4ea00ef9fe29f87ae151faeaced840f"
            )
        )
        .GET()
        .build()
    val response: HttpResponse<String> = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString())
    try {
        val jsonObject = JSONObject.parseObject(response.body())
        val error_code = jsonObject.getIntValue("error_code")
        if (error_code == 0) {
            println("调用接口成功")
            val result = jsonObject.getJSONObject("result")
            val realtime = result.getJSONObject("realtime")
            System.out.printf("城市：%s%n", result.getString("city"))
            System.out.printf("天气：%s%n", realtime.getString("info"))
            System.out.printf("温度：%s%n", realtime.getString("temperature"))
            System.out.printf("湿度：%s%n", realtime.getString("humidity"))
            System.out.printf("风向：%s%n", realtime.getString("direct"))
            System.out.printf("风力：%s%n", realtime.getString("power"))
            System.out.printf("空气质量：%s%n", realtime.getString("aqi"))
            val futures = result.getJSONArray("future")
            futures.forEach(Consumer { item: Any? ->
                val future =
                    JSONObject.parseObject(JSONObject.toJSONString(item))
                val date = future.getString("date")
                val temperature = future.getString("temperature")
                val weather = future.getString("weather")
                val direct = future.getString("direct")
                println("日期：$date，温度：$temperature，天气：$weather，风向：$direct")
            })
        } else {
            println("调用接口失败：" + jsonObject.getString("reason"))
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
}